#! /bin/sh

export FROM_CHARMRUN='1'

pre_args=''
cmd=""
args=""
QUIET=0
XTERM='xterm'
DEBUG=0
DEBUG_NO_PAUSE=0
DEBUGGER=''

while [ $# -gt 0 ]
do
        case $1 in
	+p|+ppn|++ppn)
		args="$args $1 $2"
		shift;
		shift
		;;
	++quiet)
		QUIET=1
		shift
		;;
	++no-quiet)
		QUIET=0
		shift
		;;
	++local|++no-local)
		# consume and ignore, local-mode is all that multicore supports
		shift
		;;
	++xterm)
		XTERM=$2
		shift
		shift
		;;
	++debug)
		DEBUG=1
		shift
		;;
	++no-debug)
		DEBUG=0
		shift
		;;
	++debug-no-pause)
		DEBUG_NO_PAUSE=1
		shift
		;;
	++no-debug-no-pause)
		DEBUG_NO_PAUSE=0
		shift
		;;
	++debugger)
		DEBUGGER=$2
		shift
		shift
		;;
	+*)
		args=$args" "$1
		shift
		;;
	*)
		if [ -z "$cmd" ]; then
			cmd="$1"
		else
			args=$args" "$1
		fi
		shift
		;;
	esac
done

test $QUIET -eq 1 && args=$args" "++quiet

if [ "$DEBUG" = '1' ] || [ "$DEBUG_NO_PAUSE" = '1' ]
then
  if [ -z "$DEBUGGER" ]
  then
    [ "$(uname -s 2>/dev/null)" = 'Darwin' ] && DEBUGGER='lldb' || DEBUGGER='gdb'
  fi

  DEBUG_RUN='-ex r'
  DEBUG_POSTFIX='--args'
  if [ "$DEBUGGER" = 'lldb' ]
  then
    DEBUG_RUN='-o r'
    DEBUG_POSTFIX='--'
  fi

  pre_args="$DEBUG_POSTFIX $pre_args"
  [ "$DEBUG_NO_PAUSE" = '1' ] && pre_args="$DEBUG_RUN $pre_args"
  pre_args="$XTERM -e $DEBUGGER $pre_args"
fi

test $QUIET -eq 0 && echo Running command: "$pre_args" "$cmd" "$args"
test $QUIET -eq 0 && echo

# shellcheck disable=SC2086
exec $pre_args "$cmd" $args
